import {config} from "./common";

const pub = {
    // 将ID、ParentID这种数据格式转换为树格式
    arrayToTree(data, id, pid) {      // 将ID、ParentID这种数据格式转换为树格式
        if (!data || !data.length) return [];
        let targetData = [];                    // 存储数据的容器(返回)
        let records = {};
        let itemLength = data.length;           // 数据集合的个数
        for (let i = 0; i < itemLength; i++) {
            let o = data[i];
            records[o[id]] = o;
        }
        for (let i = 0; i < itemLength; i++) {
            let currentData = data[i];

            currentData.open = false;
            if (sessionStorage.getItem('currentPid') === currentData.id) {
                currentData.open = true;
            }

            let parentData = records[currentData[pid]];
            if (!parentData && currentData.is_menu === '0') {
                targetData.push(currentData);
                continue;
            }
            // parentData.open = false;
            if (currentData.is_menu === '0') {
                parentData.children = parentData.children || [];
                parentData.children.push(currentData);
            }
        }
        return targetData;
    },

    // 将ID、ParentID这种数据格式转换为树格式(显示组织架构按钮权限操作)
    arrayToTreeList(data, id, pid) {      // 将ID、ParentID这种数据格式转换为树格式
        if (!data || !data.length) return [];
        let targetData = [];                    // 存储数据的容器(返回)
        let records = {};
        let itemLength = data.length;           // 数据集合的个数
        for (let i = 0; i < itemLength; i++) {
            let o = data[i];
            records[o[id]] = o;
        }
        for (let i = 0; i < itemLength; i++) {
            let currentData = data[i];
            currentData.open = true;
            let parentData = records[currentData[pid]];
            if (!parentData) {
                targetData.push(currentData);
                continue;
            }
            // parentData.open = false;
            parentData.children = parentData.children || [];
            parentData.children.push(currentData);
        }
        return targetData;
    },

    allMenu: [],

    loadopen() {
        this.loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.2)'
        });
        setTimeout(() => {
            this.loading.close();
        }, 5000);
    },

    loadclose() {
        this.loading.close();
    },

    // 获取当前时间格式化的字符串
    getCurrentTime(timeStr) {
        function g(t) {
            if (t < 10) {
                t = '0' + t;
            }
            return t;
        }

        Date.prototype.toLocaleString = function () {
            return this.getFullYear() + '-' + g(this.getMonth() + 1) + '-' + g(this.getDate())
                + ' ' + g(this.getHours()) + ':' + g(this.getMinutes()) + ':' + g(this.getSeconds());
        };
        let str = timeStr ? timeStr : new Date().getTime();
        let time = new Date(str);
        time = time.toLocaleString();
        return time;
    },
    // OSS文件上传（签名上传）
    OssUpload(file, callBack) {
        config.get('/upload/getUploadPolicyAndSign', {}).then(sig=>{
            let param = sig.data;
            let _date = new Date() * 1;
            let fileName = _date + '.' + file.name.split('.')[1];
            let fileFullName = param.host + '/' + param.dir + fileName;
            var request = new FormData();
            request.append('OSSAccessKeyId', param.accessid);
            request.append('policy', param.policy);
            request.append('Signature', param.signature);
            request.append('key', `${param.dir}${fileName}`);
            request.append('file', file);
            request.append('name', file.name);
            $.ajax({
                url: param.host,
                data: request,
                processData: false,
                cache: false,
                async: false,
                contentType: false,
                //关键是要设置contentType 为false，不然发出的请求头 没有boundary
                //该参数是让jQuery去判断contentType
                type: "POST",
                success: function (data, textStatus, request) {
                    if (textStatus === "nocontent") {
                        callBack(fileFullName);
                    } else {
                        alert(textStatus);
                    }
                }
            });
        })
    },
    // 文件上传-OSS前端直传（jzkj02-OSS）
    ossupFile(el,back){
        //先获取oss授权
        let clientParam = {
            region: "oss-cn-hangzhou", //阿里云获取
            accessKeyId: "LTAITgXWmdLaLlYq",
            accessKeySecret: "UoPJ9Z0MhK5VIVv86fo1rB7aHbFULH",
            bucket: "jzkj02",  //要存储的目录名
            stsToken: '',
            endpoint: '',
        };
        if(!clientParam ){
            alert('暂未授权！');
            return;
        }
        let client = new OSS(clientParam);
        // ----步骤2-------------------------------------------------
        var tempCheckpoint;
        var suffix = el.value.substr(el.value.indexOf(".")); // 获取文件后缀名
        var filename = pub.randomString(3)+new Date().getTime() + suffix; // 为文件命名
        // client.multipartUpload("tracingsource/" + filename, el.files[0], {
        client.multipartUpload("file/" + filename, el.files[0], {
            parallel: 5, //并行上传的分片个数
            progress: async function (p, checkpoint) {
                tempCheckpoint = checkpoint;
                // console.log(p)
            },
            checkpoint: tempCheckpoint,
            mime: 'text/plain', //文件格式
            meta:  null, //标识
        }).then(function (result) {
            var url = result.res.requestUrls[0];
            var length = url.lastIndexOf('?');
            // var imgUrl = result.url || url.substr(0,length);//文件最终路径
            var imgUrl = length>0?url.substr(0,length):url;
            console.log(imgUrl);
            back(imgUrl)
            // document.querySelector('#imgp').src = imgUrl + '?x-oss-process=image/resize,w_80,h_80';
            // document.querySelector('#imgUrl').innerText = '文件地址：'+ imgUrl + '?x-oss-process=image/resize,w_80,h_80';
        }).catch(function (err) {
            console.log(err);
        });
    },
    // 生成指定位数的随机字符串
    randomString(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = '';
        let i = 0;
        for (i; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    },
    // 解析URL地址
    GetRequest() {
        var url = location.href; //获取url中"?"符后的字串
        var theRequest = new Object();
        var strs;
        if (url.indexOf("?") != -1) {
            var str = url.substr(url.indexOf("?")+1);
            strs = str.split("&");
            for(var i = 0; i < strs.length; i ++) {
                theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    },
    viewBigImg(url){
        var div =
            `<div onclick="document.getElementById('viewImg').innerHTML = ''"
                    style="position: fixed;display: flex;justify-content: center;align-items: center;
                    background: #000;width: 100%;height: 100%;top: 0;left: 0;"
                >
                    <img src="${url}" alt="" style="width: 100%;">
             </div>`;
        document.getElementById('viewImg').innerHTML = div;
    }
};

export default pub;
